package com.ahm.service;


import com.ahm.base.BaseService;
import com.ahm.bean.Permission;
import com.ahm.bean.Role;
import com.ahm.dto.TreeNode;
import com.ahm.mapper.ModuleMapper;
import com.ahm.mapper.PermissionMapper;
import com.ahm.mapper.RoleMapper;
import com.ahm.query.RoleQuery;
import com.ahm.utils.AssertUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.xml.crypto.Data;
import java.util.*;

@Service
public class RoleService extends BaseService<Role,Integer> {


    @Autowired(required = false)
    private RoleMapper roleMapper;

    @Resource
    private PermissionMapper permissionMapper;

    @Resource
    private ModuleMapper moduleMapper;


    /**
     * 查询所有的角色
     * @return
     */
    public List<Map<String,Object>> findRoles(Integer userId){
        if (userId==null){
            userId = 0;
        }
        //返回目标集合对象
       return roleMapper.selectRoles(userId);
    }


    /**
     * 角色的条件查询
     * @param query
     * @return
     */
    public Map<String,Object> findAllRole(RoleQuery query){
        //查询
        List<Role> rlist = roleMapper.selectByParams(query);
        //实例化Map
        Map<String,Object> map=new HashMap<>();
        //准备列表展示的数据
        map.put("code",0);
        map.put("msg","success");
        map.put("count",rlist.size());
        map.put("data",rlist);
        //返回目标数据
        return  map;
    }

    public void insertRole(Role role) {
        // 校验
        checkRoleParams(role.getId(),role.getRoleName(),role.getRoleRemark());
        System.out.println("2222222222222222233333333333");
        // 设置默认值
        role.setIsValid(1);
        role.setIsValid(1);
        role.setCreateDate(new Date());
        role.setUpdateDate(new Date());
        System.out.println(role);
        //是否添加成功
        AssertUtil.isTrue(roleMapper.insertRole(role)<0,"添加失败");

    }

    private void checkRoleParams(Integer id, String roleName,String roleRemark) {
        if (id!=null){
            // 判断id 是否存在
            AssertUtil.isTrue(roleMapper.selectByPrimaryKey(id)!=null,"该用户已经存在");
        }
        AssertUtil.isTrue(StringUtils.isBlank(roleName),"角色名称不能为空");
        AssertUtil.isTrue(StringUtils.isBlank(roleRemark),"角色描述不能为空");
        // 判断角色是否已经存在
        AssertUtil.isTrue(roleMapper.selectByRoleName(roleName)>0,"该角色已经存在，请勿重复添加");


    }

    public void updateRole(Role role) {
        // 校验
        checkRoleUpdateParams(role.getId(),role.getRoleName(),role.getRoleRemark());
        // 设置默认值
        role.setUpdateDate(new Date());
        // 更新是否成功
        AssertUtil.isTrue(roleMapper.updateByPrimaryKeySelective(role)<1,"更新失败");
    }

    private void checkRoleUpdateParams(Integer id, String roleName, String roleRemark) {
        // 要更新的用户是否存在
        AssertUtil.isTrue(roleMapper.selectByPrimaryKey(id)==null || id ==null,"要更新的记录不存在");
        // 角色名是否存在
        Role role = roleMapper.selectRoleByRoleName(roleName);
        AssertUtil.isTrue(role!=null,"该角色已存在，更新失败");
        //
        AssertUtil.isTrue(StringUtils.isBlank(roleRemark),"角色描述不能为空");

    }

    public void addGrant(Integer[] mids, Integer roleId) {
        // 验证roLeId是否存在
        AssertUtil.isTrue(roleMapper.selectByPrimaryKey(roleId)==null,"要授权的角色不存在");
      //   角色原来时候有资源 有的话删除
         //  select count(*) from permission where roleId = #{roleId}
        int count = permissionMapper.selectModuleCountByRoleId(roleId);
        if (count>0){
            // 根据 roleId 删除Permission 中对应的记录
            // delete from permission where roleId = #{roleId}
            AssertUtil.isTrue(permissionMapper.deleteByRoleIdFromPermission(roleId)!=count,"授权异常");;
        }

        // 遍历mids 进行添加
        ArrayList<Permission> permissions = new ArrayList<Permission>();
        // 查询所有的权限
        // 设置默认值
        for (Integer mid :mids){
            Permission permission = new Permission();
            permission.setRoleId(roleId);
            permission.setModuleId(mid);
            if (count==0){
                permission.setCreateDate(new Date());
            }
            permission.setUpdateDate(new Date());
            // 根据 mid 查询 对应的权限码
            // select parent_opt_value from t_module where id =#{mid}
            String aclValue = moduleMapper.selectAclValue(mid);
            AssertUtil.isTrue(StringUtils.isBlank(aclValue),"权限码异常");
            permission.setAclValue(aclValue);
            // 添加到集合中
            permissions.add(permission);
        }
        // 批量添加
        AssertUtil.isTrue(permissionMapper.insertPermissions(permissions)!=mids.length,"授权失败");

    }
}
